/**
 *
 * @description:【service】层相关工具类方法
 * @author:翟磊
 * @date:2022-02-15
 *
 **/
import Qs from "qs";
const { host } = require("@/environment/index.js");
//构建完整的请求url
function rebuildUrl(config = {}) {
  let { baseUrl, url } = config;
  return (host[baseUrl] + url).trim();
}

// 用于根据当前请求的信息，生成请求 Key
function generateReqKey(config) {
  const { method, url, params, data } = config;
  return [method, url, Qs.stringify(params), Qs.stringify(data)].join("&");
}

//用于存储当前请求信息
const pendingRequest = new Map();
function addPendingRequest(config, axiosInstance) {
  const requestKey = generateReqKey(config);
  config.cancelToken =
    config.cancelToken ||
    new axiosInstance.CancelToken((cancel) => {
      if (!pendingRequest.has(requestKey)) {
        pendingRequest.set(requestKey, cancel);
      }
    });
}

//检查是否存在重复请求，若存在则取消已发的请求
function removePendingRequest(config) {
  const requestKey = generateReqKey(config);
  if (pendingRequest.has(requestKey)) {
    const cancelToken = pendingRequest.get(requestKey);
    // cancelToken(requestKey);
    pendingRequest.delete(requestKey);
  }
}

export { rebuildUrl, generateReqKey, addPendingRequest, removePendingRequest };
